﻿using System.Net;
using MolyMade.Http.Base;
using MolyMade.Http.DataTypes;

namespace MolyMade.Http.Controller
{
    public static class Controller
    {
        public static Response Request(Request request)
        {
            BaseRequest baseRequest = new BaseRequest
            {
                Url = Utilities.Utilities.ConcatParameters(request.Url, request.Parameters),
                HttpMethod = request.HttpMethod,
                ConnectionTimeout =  request.ConnectionTimeout,
                ReadWriteTimeout = request.ReadWriteTimeout,
                CookieCollection = request.Cookies,
                PostBuffer = request.PostBuffer,
                Proxy = request.Proxy,
                ProxyUserName = request.ProxyUserName,
                ProxyPassword = request.ProxyPassword,
                CerPath = request.CerPath,
                CerPwd = request.CerPwd,
                AllowAutoRedirect = request.AllowAutoRedirect,
                Expect100Continue = request.Expect100Continue,
                ProtoVersion = request.ProtoVersion,
                IpEndPoint = request.IpEndPoint,
                MaxAutoRedirection = request.MaxAutoRedirection,
                MaxConnection = request.MaxConnection
            };
            if (request.Headers != null)
            {
                SetHeaders(baseRequest, request.Headers);
            }
            HttpWebResponse httpWebResponse = baseRequest.GetResponse();
            return new Response(request,httpWebResponse,baseRequest.Elasped);
        }  

        private static void SetHeaders(BaseRequest request, Headers headers)
        {
            request.Accept = headers.Accept;
            request.Connection = headers.Connection;
            request.ContentType = headers.ContentType;
            request.Date = headers.Date;
            request.Expect = headers.Expect;
            request.Expect100Continue = headers.Expect100Continue;
            request.IfModifiedSince = headers.IfModifiedSince;
            request.KeepAlive = headers.KeepAlive;
            request.Referer = headers.Referer;
            request.UserAgent = headers.UserAgent;
            request.HeaderCollection = headers.HeaderCollection;
        }
    }
}
